package leetcode.D100.T98;

import util.TreeNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-19 16:22:13 星期四
 */

public class Solution {
    // 一刷
    /*public boolean isValidBST(TreeNode root) {
        if(root == null) {
            return true;
        }
        if(root.left != null) {
            TreeNode left = root.left;
            while(left.right != null) {
                left = left.right;
            }
            if(root.val <= left.val || !isValidBST(root.left)) {
                return false;
            }
        }
        if(root.right != null) {
            TreeNode right = root.right;
            while(right.left != null) {
                right = right.left;
            }
            if (root.val >= right.val || !isValidBST(root.right)) {
                return false;
            }
        }
        return true;
    }*/

    // 二刷
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        if (root.left != null) {
            TreeNode right = root.left;
            while (right.right != null)
                right = right.right;
            if (root.val <= right.val)
                return false;
        }
        if (root.right != null) {
            TreeNode left = root.right;
            while (left.left != null)
                left = left.left;
            if (root.val >= left.val)
                return false;
        }
        return isValidBST(root.left) && isValidBST(root.right);
    }
}
